import Taro from "@tarojs/taro";

/**
 * 校验特殊字符串
 * @param value 输入内容
 */
export const verityInputValue = (value: string) => {
  const pattern = /^(\w|[^\x00-\xff]|[:,-|;])*$/;
  return pattern.test(value);
};

/**
 * 判断是否是数组
 * @param value
 */
export function isArray(value: any) {
  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  } else {
    return Object.prototype.toString.call(value) === "[object Array]";
  }
}

/**
 * 路由跳转
 * @param url 页面相对路径
 * @param params 路由参数
 * @returns
 */
export function pushTo(url: string, params?: any) {
  let _url = url
  if (params) {
    let newParams = "";
    for (let k in params) {
      newParams += `&${k}=${params[k]}`;
    }
    newParams = newParams.replace(/&/, "?");
    _url = _url + newParams
  }
  Taro.navigateTo({
    url: _url
  });
}


/**
 * 获取url路径参数
 * @param url url
 * @returns 路径参数对象
 */
export function getQueryUrl(url: string) {
  if (url && url.length <= 0) return {};
  var queryObj = {};
  var query = url.split("?")[1];
  if (query) {
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      queryObj[pair[0]] = pair[1];
    }
    return queryObj;
  } else {
    return {};
  }
}


/**
 * 时间戳换算成时分秒
 * @param value 时间戳 单位秒
 * @returns 时分秒
 */
export function dateConvert(value: number) {
  let hour: number
  let min: number
  let sec: number
  let createDate: string = ""
  hour = parseInt((value / 60 / 60).toString());
  min = parseInt(((value - hour * 3600) / 60).toString());
  sec = parseInt((value - (hour * 3600 + min * 60)).toString());
  if (hour > 0) {
    if (min > 0) {
      if (sec > 0) {
        createDate = hour + "时" + min + "分" + sec + "秒";
      } else {
        createDate = hour + "时" + min + "分";
      }
    } else {
      if (sec > 0) {
        createDate = hour + "时" + sec + "秒";
      } else {
        createDate = hour + "时";
      }
    }
  } else if (min > 0) {
    createDate = sec > 0 ? min + "分" + sec + "秒" : min + "分";
  } else if (sec > 0) {
    createDate = sec + "秒";
  }
  return createDate;
}

/**
 * 手机号中间设置为****
 * @param phoneNum 手机号
 * @returns 修改之后的手机号，例如：135****1234
 */
export function fuzzyNumber(phoneNum: string) {
  if (!phoneNum) return;
  return phoneNum.replace(/^(\d{3})\d{4}(\d+)/, "$1****$2");
}

/**
 * 是否是iPhoneX
 * @param info 设备信息
 * @returns 布尔值
 */
export function isIphoneXSeries(info: Taro.getSystemInfo.Result) {
  return info ?.system ?.toLowerCase().includes("ios") && info.statusBarHeight > 20;
}



/**
 * 校验手机号
 * @param phone 手机号
 */
export function verifyPhone(phone: string): boolean {
  return /^1[345789]\d{9}$/.test(phone);
}

/**
 * 输入框防抖
 * @param func 实际要执行的函数
 * @param wait 延迟时间，也就是阈值，单位是毫秒（ms）
 * @param immediate 立即
 */
export const debounce = (func: (res:any) => void, wait: number, immediate?: boolean) => {
  let timeout: any;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      if (!immediate) func.apply(this, args);
    }, wait);
    if (immediate && !timeout) func.apply(this, [...args]);
  };
};

/**
 * 节流函数
 * @param func 实际要执行的函数
 * @param delay  延迟时间，也就是阈值，单位是毫秒（ms）
 */
export const throttle = (func: (res: any) => void, delay: number)=> {
  var ctx;
  var args;
  // 记录上次触发事件
  var previous = Date.now();

  var later = function () {
    func.apply(ctx, args);
  };

  return function () {
    ctx = this;
    args = arguments;
    var now = Date.now();
    // 本次事件触发与上一次的时间比较
    var diff = now - previous - delay;

    // 如果隔间时间超过设定时间，即再次设置事件触发的定时器
    if (diff >= 0) {
      // 更新最近事件触发的时间
      previous = now;
      setTimeout(later, delay);
    }
  };
}

/**
 * 对象浅比较
 * @param {object} a
 * @param {object} b
 * @returns
 */
export function shallowEqual(a?: object, b?: object) {
  if (a === b) return true;

  if(a === undefined || b === undefined) {
    return false
  }

  let keysA = Object.keys(a);
  let keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  let hasDiff = keysA.some(key => a[key] !== b[key]);
  return !hasDiff;
}

/*
*判断文件是否是gif
* @param filePath 小程序的模板路径
* @param isMulti 是否是多选
*/
export const isGifFun = (filePath: string, isMulti = false) => {
  let isGif = false;
  const view = Taro.getFileSystemManager().readFileSync(
    filePath,
    "hex"
  );
  let v = String(view)
    .slice(0, 8)
    .toUpperCase();
  if (v === "47494638") {//过滤掉格式为gif的文件
    isGif = true;
    if (!isMulti) {
      Taro.showToast({
        title: '图片格式错误，请重新选择',
        icon: 'none',
        duration: 1000
      })
    }

  }
  return isGif;
}
